package com.lx.rpc.framework.protocol.http;

import com.alibaba.fastjson.JSONObject;
import com.lx.rpc.framework.base.Invocation;
import com.lx.rpc.framework.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 处理具体的逻辑
 * @author wcy
 */
public class HttpServerHandler {



    public void handler(HttpServletRequest req, HttpServletResponse resp){

        try {
            //获取消费者传输的数据
            ObjectInputStream ois = new ObjectInputStream(req.getInputStream());
            Invocation invocation = (Invocation)ois.readObject();
            //获取接口名称
            String interfaceName = invocation.getInterfaceName();
            //获取方法名称
            String methodName = invocation.getMethodName();
            //获取参数类型列表
            Class[] paramTypes = invocation.getParamTypes();
            //获取参数列表
            Object[] params = invocation.getParams();

            //注册表获取服务实现
            Class service = LocalRegister.getService(interfaceName);
            //拿到服务实现类的方法
            Method method = service.getMethod(methodName, paramTypes);
            String result = (String)method.invoke(service.newInstance(), params);
            IOUtils.write(result,resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }



}
